package com.platform.mall.controller.admin;

import com.platform.mall.common.exception.BadRequestException;
import com.platform.mall.common.result.Result;
import com.platform.mall.model.dto.DictDetailDto;
import com.platform.mall.model.dto.DictDetailQueryParam;
import com.platform.mall.model.entity.SysDictDetail;
import com.platform.mall.service.ISysDictDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "字典项接口")
@RestController
@RequestMapping("/api/v1/dictDetail")
@RequiredArgsConstructor
public class SysDictDetailController {

    private final ISysDictDetailService dictDetailService;
    private static final String ENTITY_NAME = "dictDetail";

    @ApiOperation("查询字典详情")
    @GetMapping("/page")
    public Result<Object> page(DictDetailQueryParam query,
                               @PageableDefault(sort = {"dictSort"}, direction = Sort.Direction.ASC) Pageable pageable) {
        return Result.success(dictDetailService.findForPage(query, pageable));
    }

    @ApiOperation("查询多个字典详情")
    @GetMapping(value = "/map")
    public Result<Object> getDictDetailMaps(@RequestParam String dictName) {
        String[] names = dictName.split("[,，]");
        Map<String, List<DictDetailDto>> dictMap = new HashMap<>(5);
        for (String name : names) {
            dictMap.put(name, dictDetailService.getDictByName(name));
        }
        return Result.success(dictMap);
    }

    @ApiOperation("新增字典详情")
    @PostMapping("/add")
    public Result<Object> create(@Validated @RequestBody SysDictDetail resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        dictDetailService.save(resources);
        return Result.success(HttpStatus.CREATED);
    }

    @ApiOperation("修改字典详情")
    @PutMapping("/update")
    public Result<Object> update(@RequestBody SysDictDetail resources) {
        dictDetailService.updateById(resources);
        return Result.success(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("删除字典详情")
    @DeleteMapping(value = "/delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        dictDetailService.removeById(id);
        return Result.success();
    }

}
